package com.mvd.app.screenShot;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;

import com.mvd.app.application.MessageEvent;
import com.mvd.app.commons.UtilsLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ScreenShotHelper {

    public interface OnScreenShotListener {
        void onFinish(Bitmap bitmap);
    }

    private OnScreenShotListener mOnScreenShotListener;

    private ImageReader mImageReader;
    private MediaProjection mMediaProjection;
    private VirtualDisplay mVirtualDisplay;
    private final SoftReference<Context> mRefContext;
    private Context context;

    public ScreenShotHelper(Context context, int resultCode, Intent data, OnScreenShotListener onScreenShotListener) {
        this.mOnScreenShotListener = onScreenShotListener;
        this.mRefContext = new SoftReference<Context>(context);
        this.context = context;
        mMediaProjection = getMediaProjectionManager().getMediaProjection(resultCode, data);
        mImageReader = ImageReader.newInstance(getScreenWidth(), getScreenHeight(), PixelFormat.RGBA_8888, 1);
    }

    public void startScreenShot() {
        createVirtualDisplay();
        EventBus.getDefault().register(this);
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                new CreateBitmapTask().execute();
            }
        }, 1000);
    }

    public class CreateBitmapTask extends AsyncTask<Image, Void, Bitmap> {

        @Override
        protected Bitmap doInBackground(Image... params) {
            Image image = mImageReader.acquireLatestImage();
            int width = image.getWidth();
            int height = image.getHeight();
            final Image.Plane[] planes = image.getPlanes();
            final ByteBuffer buffer = planes[0].getBuffer();

            int pixelStride = planes[0].getPixelStride();

            int rowStride = planes[0].getRowStride();
            int rowPadding = rowStride - pixelStride * width;
            Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
            bitmap.copyPixelsFromBuffer(buffer);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
            image.close();

            saveImageToGallery(bitmap);
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            mVirtualDisplay.release();
            mMediaProjection.stop();

            if (mOnScreenShotListener != null) {
                mOnScreenShotListener.onFinish(bitmap);
            }
        }
    }

    public int saveImageToGallery(Bitmap bmp) {
        //生成路径
          String root = Environment.getExternalStorageDirectory()+ "/";
//        String root = Environment.getExternalStorageDirectory().getAbsolutePath();
        String dirName = "screenImages";
//        Log.e("tag", "root==="+root);
        File appDir = new File(root, dirName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
//        if (!appDir.getParentFile().exists()){
//            appDir.getParentFile().mkdirs();
//        }
        //文件名为时间
        long timeStamp = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sd = sdf.format(new Date(timeStamp));
        String fileName = sd + ".jpg";
//        Log.e("tag", "fileName==="+fileName);
        //获取文件
        File file = new File(appDir, fileName);
        FileOutputStream fos = null;
        try {
//            Log.e("tag", "zzzzzz=appDir="+appDir);
//            Log.e("tag", "zzzzzz=fileName="+fileName);
            Log.e("tag", "zzzzzz=path="+appDir+"/"+fileName);
            EventBus.getDefault().post(new MessageEvent(file.getPath(),appDir.toString()));
            fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            //通知系统相册刷新
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                    Uri.fromFile(new File(file.getPath()))));
            return 2;
        } catch (FileNotFoundException e) {
            Log.e("tag", "aaaaa"+e.toString());
            e.printStackTrace();
        } catch (IOException e) {
            Log.e("tag", "bbbb"+e.toString());
            e.printStackTrace();
        } finally {

            try {
                if (fos != null) {
                    fos.close();
                }
                Log.e("tag", "xxxxxxx");
            } catch (IOException e) {
                Log.e("tag", "cccc"+e.toString());
                e.printStackTrace();
            }
        }
        return -1;
    }

    private MediaProjectionManager getMediaProjectionManager() {
        return (MediaProjectionManager) getContext().getSystemService(
                Context.MEDIA_PROJECTION_SERVICE);
    }

    private void createVirtualDisplay() {
        mVirtualDisplay = mMediaProjection.createVirtualDisplay(
                "screen-mirror",
                getScreenWidth(),
                getScreenHeight(),
                Resources.getSystem().getDisplayMetrics().densityDpi,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                mImageReader.getSurface(),
                null,
                null
        );
    }

    private Context getContext() {
        return mRefContext.get();
    }

    public static int getScreenWidth() {
        return Resources.getSystem().getDisplayMetrics().widthPixels;
    }

    public static int getScreenHeight() {
        return Resources.getSystem().getDisplayMetrics().heightPixels;
    }
    @Subscribe(threadMode = ThreadMode.POSTING)
    public void getFilePathEventBus(final MessageEvent event) {
        UtilsLog.e("截图路径=ScreenShotHelper=" + event.getMessage());
        UtilsLog.e("截图路径=ScreenShotHelper=" + event.getPath());
//        if (event != null) {
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    Message msg = new Message();
//                    msg.obj = event.getMessage();
//                    handler_main.sendMessage(msg);
//                }
//            }).start();
//        }
    }

}